package com.sbdev.controller;


import com.sbdev.dic.SexEnum;
import com.sbdev.pojo.User;
import com.sbdev.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/redis")
public class RedisController {
    // StringRedisTemplate是RedisTemplate的子类，但是该属性名“redisTemplate”和Bean名称一致，
    // 因此可以使用@Autowired注入，如果属性名称不为“redisTemplate”，则注入失败，抛出异常
    @Autowired
//    private RedisTemplate<Object, Object> redisTemplate = null;
    private RedisTemplate<String, Object> redisTemplate = null;

    // 注入StringRedisTemplate
    @Autowired
    private StringRedisTemplate stringRedisTemplate = null;

    // 测试字符串
    @GetMapping("/string/{key}/{value}")
    public Map<String, String> string(@PathVariable("key") String key, @PathVariable("value") String value) {
        stringRedisTemplate.opsForValue().set(key, value);
        Map<String, String> result = new HashMap<>();
        result.put(key, value);
        return result;
    }

    // 测试对象
    @GetMapping("/object/{id}")
    public User object(@PathVariable("id") Long id){
        User user = new User();
        user.setId(id);
        user.setUserName("user_name" + id);
        user.setNote("note_" + id);
        user.setSex(SexEnum.getSexEnum(id.intValue() % 2));
        redisTemplate.opsForValue().set("user_" + id, user);
        return user;
    }

    @Autowired
    private UserService userService = null;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Long id) {
        return userService.getUser(id);
    }
}
